const { errorModel } = require("../models/errorModels");

// 错题删除
async function deleteErrors(req, res, next) {
  //_id为需要删除的错误题目的_id
  const { _id } = req.body;
  const result = await errorModel.deleteOne({ _id });
  if (result.deletedCount != 0) {
    res.send({
      message: "删除成功",
      code: 200
    });
  } else {
    res.send({
      message: "删除失败",
      code: 500
    });
  }
}
// 错题获取所有数据接口
async function getErrors(req, res, next) {
  //传入{studentId}
  const { studentId } = req.body;
  // console.log(studentId);
  const result = await errorModel.find({ studentId }).populate("exerciseId");
  // console.log(result);
  if (result.length > 0) {
    res.send({
      code: 200,
      message: "获取数据成功",
      result
    });
  } else {
    res.send({
      code: 500,
      message: "获取数据失败"
    });
  }
}
// 添加错误题目
async function createErrors(req, res, next) {
  //前端需要传入{exerciseId,studentId,errorAnswer}
  const { exerciseId, studentId, errorAnswer } = req.body;
  const result = await errorModel.find({ exerciseId, studentId, errorAnswer });
  if (result.length == 0) {
    let resultCreate = await errorModel.create({
      exerciseId,
      studentId,
      errorAnswer
    });
    // console.log(resultCreate);
    if (resultCreate) {
      res.send({
        message: "添加成功",
        code: 200
      });
    } else {
      res.send({
        message: "添加失败",
        code: 500
      });
    }
  } else {
    res.send({
      code: 500,
      message: "错题已存在"
    });
  }
}

module.exports = {
  deleteErrors,
  getErrors,
  createErrors
};
